const watermarkId = "watermark_251dc"
const interval = 5 * 1000;
// 添加水印的函数
function addWatermark(msg, addTime) {
  const canvas = document.createElement('canvas');
  canvas.width = 200;
  canvas.height = 80;
  const canvas2D = canvas.getContext('2d');
  canvas2D.rotate(-20 * Math.PI / 180);  //水印文本的旋转角度
  canvas2D.font = '15px Arial';      //设置字体
  canvas2D.fillStyle = '#666666';
  canvas2D.textAlign = 'center';
  canvas2D.textBaseline = 'middle';
  canvas2D.fillText(msg, canvas.width / 2, canvas.height - 10);
  if (addTime) {
    canvas2D.fillText(getFormatedTime(), canvas.width / 2, canvas.height + 10);
  }
  const watermark = document.createElement('div');
  watermark.id = watermarkId;
  watermark.style.whiteSpace='nowrap'     //来保证水印文本不换行
  watermark.style.pointerEvents = 'none';
  watermark.style.position = 'fixed';     //使水印相对于视口固定位置
  watermark.style.top = '40px';           //top和bottom：设置水印元素距离视口顶部或底部的距离
  watermark.style.left = '0';             //设置水印元素距离视口左部或右部的距离
  watermark.style.fontSize='20px'         //水印文本的大小
  watermark.style.width = '100%';
  watermark.style.height = '100%';
  watermark.style.opacity = '0.15'    //透明度
  watermark.style.zIndex = '9999';
  watermark.style.background = `url(${canvas.toDataURL('image/png')}) left top repeat`;
  document.body.appendChild(watermark);
}

function getFormatedTime() {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}`;
}

// 移除水印的函数
function removeWatermark() {
  const watermark = document.getElementById(watermarkId);
  if (watermark !== null) {
    document.body.removeChild(watermark);
  }
}

// 初始化水印的函数，包含自己的逻辑
function initWatermark(msg, addTime = true) {
  addWatermark(msg, addTime);
  let timer = setInterval(() => {
	  removeWatermark();
	  addWatermark(msg, addTime);
  }, interval);
  window.addEventListener('unload', () => {
    clearInterval(timer)
  });
}

// 导出初始化水印的方法
export { initWatermark as default };

